import time
from concurrent.futures import ThreadPoolExecutor, wait
from datetime import date
from typing import Final

import undetected_chromedriver as uc
from faker import Faker
from loguru_extra import traceable, add_file_logger, logger
from selenium.common import NoSuchElementException, ElementNotInteractableException

from do_with_element import DoWithElement

GOOGLE_URL: Final[str] = "https://google.com"
COUNT_ACC: Final[int] = 1
IGNORE_ERRORS = [NoSuchElementException, ElementNotInteractableException]

add_file_logger("log.log")


@traceable
def main(_fk: Faker):
    logger.info("Старт создания аккаунта через selenium")
    first_name = _fk.first_name()
    last_name = _fk.last_name()
    date_of_birth: date = _fk.date_of_birth()
    day_of_birth = date_of_birth.day
    month_of_birth = date_of_birth.month
    year_of_birth = date_of_birth.year
    gender = _fk.passport_gender()
    gender_index = [1, 2][1 if gender == 'F' else 0]
    password = _fk.password()

    driver = uc.Chrome()
    driver.implicitly_wait(0.2)
    driver.get(GOOGLE_URL)
    DoWithElement("a.gb_Ba.gb_md.gb_Od.gb_me", driver).click().do()
    DoWithElement("input[type='email']", driver).click().input_word("галкин антон").do()
    (DoWithElement("button[aria-haspopup='menu']", driver)
     .click().do())
    DoWithElement("li[role='menuitem']:nth-of-type(1)", driver).click().do()
    DoWithElement("#firstName", driver).click().input_word(first_name).do()
    DoWithElement("#lastName", driver).click().input_word(last_name).do()
    DoWithElement("#collectNameNext button", driver).click().do()
    DoWithElement("#day", driver).click().input_word(str(day_of_birth)).do()
    DoWithElement("#month", driver).click().do().select().select_by_index(month_of_birth)
    DoWithElement("#year", driver).click().input_word(str(year_of_birth)).do()
    DoWithElement("#gender", driver).click().do().select().select_by_index(gender_index)
    DoWithElement("#birthdaygenderNext button", driver).click().do()
    DoWithElement("[aria-labelledby='selectionc2'][aria-posinset='1']", driver).click().do()
    DoWithElement("#next button", driver).click().do()
    DoWithElement("#passwd input", driver).click().input_word(password).do()
    DoWithElement("#confirm-passwd input", driver).click().input_word(password).do()
    DoWithElement("#createpasswordNext button", driver).click().do()


if __name__ == '__main__':
    fk = Faker("ru_RU")
    # Не указываем количество потоков, т.к. по умолчанию берется от максимума ядер
    with ThreadPoolExecutor(thread_name_prefix="REG-") as e:
        tasks = [e.submit(main, fk) for __ in range(1)]
    wait(tasks)
    time.sleep(300)
